﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Smith.WPF.HtmlEditor;
using System.Windows.Threading;
using mshtml;
using MCDirectBroadcast.Entity;

namespace MCDirectBroadcast.Pages
{
	/// <summary>
	/// Interaction logic for AddEditStory.xaml
	/// </summary>
	public partial class AddEditStory : Window
	{
		public Story StoryItem { get; set; }

		public AddEditStory()
		{
			InitializeComponent();
			InitEvents();
		}

		void LoadEdit()
		{
			if (StoryItem != null)
			{
				TbTitle.Text = StoryItem.Title;
				TbLoc.Text = StoryItem.Location;
				TbTime.Text = StoryItem.TimeToGo;
				TbDirectby.Text = StoryItem.Owner;
				Editor.ContentHtml = StoryItem.Content;
			}
		}

		void InitEvents()
		{
			Editor.DocumentReady += new RoutedEventHandler(Editor_DocumentReady);
			BtnCancel.Click += new RoutedEventHandler(BtnCancel_Click);
			BtnSave.Click += new RoutedEventHandler(BtnSave_Click);
			this.Loaded += new RoutedEventHandler(AddEditStory_Loaded);
		}

		void AddEditStory_Loaded(object sender, RoutedEventArgs e)
		{
			
		}

		void BtnSave_Click(object sender, RoutedEventArgs e)
		{
			string title = TbTitle.Text;
			string loc = TbLoc.Text;
			string time = TbTime.Text;
			string owner = TbDirectby.Text;
			string content = Editor.ContentHtml;

			Story stry = new Story()
			{
				ID = StoryItem != null ? StoryItem.ID : -1,
				Title = title,
				TimeToGo = time,
				Location = loc,
				Content = content,
				CreateDate = DateTime.Now,
				Owner = owner
			};

			int r = -1;
			if (StoryItem != null)
				r = SQLCeHelper.UpdateStory(stry);
			else
				r = SQLCeHelper.InsertStory(stry);

			if(r > 0)
			{
				MessageBox.Show("Story \"" + Title + "\" has been saved.", "Notification Message", MessageBoxButton.OK, MessageBoxImage.Information);
				ClearForm();
			}
			else
			{
				MessageBox.Show("Can't save this story please verify your inputs.", "Notification Message", MessageBoxButton.OK, MessageBoxImage.Error);
			}
		}

		void BtnCancel_Click(object sender, RoutedEventArgs e)
		{
			this.Close();
		}

		void ClearForm() 
		{
			TbTitle.Text = string.Empty;
			TbLoc.Text = string.Empty;
			TbTime.Text = string.Empty;
			TbDirectby.Text = string.Empty;
			Editor.ContentHtml = string.Empty;
		}

		void Editor_DocumentReady(object sender, RoutedEventArgs e)
		{
			LoadEdit();
			//Editor.ContentHtml = "<p><b>Smith Html Editor</b></p><p><a href=\"http://smithhtmleditor.codeplex.com\">http://smithhtmleditor.codeplex.com/</a></p>";
		}

	}
}
